const app = getApp(); //引入导航

var util = require('../../utils/common.js'); //引入公共JS
//var wxParse = require('../../wxParse/wxParse.js'); //引入


import { YcTicket } from 'ycTicket_model.js';
import { Address } from '../../utils/address.js';
var ycTicket = new YcTicket();
var address = new Address();
var dataName = '';
var idcards = '';
Page({
  data: {
    showIcon: true,
    //显示返回键以及首页
    provinceName: [],
    provinceCode: [],
    provinceSelIndex: '',
    cityName: [],
    cityCode: [],
    citySelIndex: '',
    districtName: [],
    districtCode: [],
    showMessage: false,
    showDistpicker: false,
    wayFlag: true,
    //支付方式切换
    serviceIs: "是",
    //是否同意用户协议
    userMessage: true,
    serviceFlag: true,
    //是否显示用户协议
    tabArr: {
      // tab 切换
      curHdIndex: 0,
      curBdIndex: 0
    },
    wayText1: "",
    wayText2: "",
    wayText3: "",
    nvabarData: {
      showCapsule: 1,
      //是否显示左上角图标
      title: '提交订单' //导航栏 中间的标题

    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20
  },
  onLoad: function (options) {
    console.log(options);
    var aid = options.aid;
    var num = options.num;
    var performId = options.performId;
    var quyuID = options.quyuID;
    var orderStatus = options.orderStatus; //将数据写入缓存

    tt.setStorageSync('aid', aid);
    tt.setStorageSync('performId', performId);
    tt.setStorageSync('quyuID', quyuID);
    tt.setStorageSync('num', num);
    var array = [];

    for (var i = 0; i < num; i++) {
      array[i] = i;
    }

    this.data.id = aid;
    this.data.performId = performId;
    this.data.quyuID = quyuID;
    this.data.orderStatus = orderStatus; //console.log(orderStatus)

    this.setData({
      aid: aid,
      num: num,
      array: array
    });

    this._loadDate(num);
  },
  _loadDate: function (num) {
    //特殊说明
    // ycTicket.getTebie(this.data.id, (data) => {
    //   wxParse.wxParse('article', 'html', data.tebieshuoming, this, 5);
    //   that.setData({
    //     'shuoming': data.tebieshuoming
    //   });
    // });
    var that = this;
    ycTicket.getBuKuanSJrow(this.data.id, this.data.performId, data => {
      tt.setStorageSync('datetime', data.datetime);
      that.setData({
        datetime: data.datetime
      });
    });
    ycTicket.getBuKuanPJrow(this.data.id, this.data.quyuID, data => {
      //console.log(data.Sprice * num)
      tt.setStorageSync('Sprice', data.Sprice);
      tt.setStorageSync('price', data.Sprice);
      tt.setStorageSync('orderPrice', data.Sprice * num);
      that.setData({
        Sprice: data.Sprice,
        price: data.Sprice,
        priceRow: data.Sprice * num
      });
    });
    ycTicket.getXinXi(this.data.id, data => {
      //console.log(data.idcards)
      var qupiaoStr = data.qupiaolei;
      var qupiaolei = data.qupiaolei.split(",");
      idcards = data.idcards; // this.data.idcards = idcards;

      that.setData({
        listrow: data,
        qupiaolei: qupiaolei
      }); //页面加载判断显示哪些配送方式

      if (qupiaoStr.indexOf("快递") != -1) {
        this.setData({
          wayText1: true
        });
      } else {
        this.setData({
          wayText1: false
        });
      }

      if (qupiaoStr.indexOf("电子票") != -1) {
        this.setData({
          wayText2: true
        });
      } else {
        this.setData({
          wayText2: false
        });
      }

      if (qupiaoStr.indexOf("现场取票") != -1) {
        this.setData({
          wayText3: true
        });
      } else {
        this.setData({
          wayText3: false
        });
      } //显示对应的取票方式


      var obj = {};

      if (this.data.wayText1 == true) {
        obj.curHdIndex = 1;
        obj.curBdIndex = 1;
        dataName = '快递';
      }

      if (this.data.wayText2 == true) {
        obj.curHdIndex = 2;
        obj.curBdIndex = 2;
        dataName = '电子票';
      }

      if (this.data.wayText3 == true) {
        obj.curHdIndex = 3;
        obj.curBdIndex = 3;
        dataName = '现场取票';
      }

      if (this.data.wayText1 == true && this.data.wayText2 == true) {
        obj.curHdIndex = 1;
        obj.curBdIndex = 1;
        dataName = '快递';
      }

      if (this.data.wayText2 == true && this.data.wayText3 == true) {
        obj.curHdIndex = 2;
        obj.curBdIndex = 2;
        dataName = '电子票';
      }

      if (this.data.wayText1 == true && this.data.wayText3 == true) {
        obj.curHdIndex = 1;
        obj.curBdIndex = 1;
        dataName = '快递';
      }

      if (this.data.wayText1 == true && this.data.wayText2 == true && this.data.wayText3 == true) {
        obj.curHdIndex = 1;
        obj.curBdIndex = 1;
        dataName = '快递';
      }

      tt.setStorageSync('dataName', dataName);
      this.setData({
        tabArr: obj
      });
    });
    ycTicket.getXxCc(this.data.id, data => {
      //console.log(data)
      that.setData({
        listfint: data
      });
    });
    ycTicket.getChaXun(data => {
      // console.log(data)
      that.setData({
        ChaXun: data
      });
    });
  },
  //配送方式切换
  wayClick: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    this.setData({
      tabArr: obj,
      dataName: e.target.dataset.name
    }); // wx.setStorageSync('dataName', dataName);
  },
  //选择是否同意用户协议
  switchChange: function (e) {
    var _val = e.detail.value;

    if (_val == true) {
      this.setData({
        serviceIs: "是"
      });
    } else {
      this.setData({
        serviceIs: "否"
      });
    }
  },
  editAddress: function (event) {
    var that = this;
    tt.chooseAddress({
      success: function (res) {
        // console.log(res)
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: address.setAddressInfo(res)
        };

        that._bindAddressInfo(addressInfo);
      }
    });
  },
  // 绑定地址信息
  _bindAddressInfo: function (addressInfo) {
    //console.log(addressInfo)
    this.setData({
      addressInfo: addressInfo
    });
  },
  ZhiFuGeShu: function () {
    this.showMessage('未支付订单过多，请删除后重试！');
  },

  /*下单和付款*/
  pay: function (e) {
    if (this.data.serviceIs == "否") {
      this.showMessage('请先阅读用户协议并同意!');
    } else {
      ycTicket.getChaXun(data => {
        if (data < 5) {
          if (this.data.orderStatus == 0) {
            this._firstTimePay(e);
          } else {
            this._oneMoresTimePay();
          }
        } else {
          this.showMessage('未支付订单过多，请删除后重试！');
        }
      });
    }
  },
  nameInput: function (e) {
    //监听实名登记姓名输入
    this.setData({
      TName: e.detail.value
    });
  },
  IdCardInput: function (e) {
    //监听实名登记身份证号输入
    this.setData({
      TCard: e.detail.value
    });
  },
  _firstTimePay: function (e) {
    var that = this;
    var aid = tt.getStorageSync("aid");
    var price = tt.getStorageSync("price");
    var Sprice = tt.getStorageSync("Sprice");
    var performId = tt.getStorageSync("performId");
    var pricetitle = tt.getStorageSync("pricetitle");
    var orderPrice = tt.getStorageSync("orderPrice");
    var totalCount = tt.getStorageSync("num");
    var datetime = tt.getStorageSync("datetime");
    var quyuID = tt.getStorageSync("quyuID");
    var priceID = tt.getStorageSync("priceID");
    var telRule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[1|3|5|8|9])[0-9]{8}$/,
        IdRule = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    var wayArray = [];

    if (dataName == '快递') {
      var data = e.detail.value; // var _arr = data.addresrow.split("市")[0] + "市";
      // var _arr1 = data.addresrow.split("市")[1];

      if (idcards == '是') {
        if (data.cName == '') {
          this.showMessage('请输入姓名');
        } else if (data.cTel == '') {
          this.showMessage('请输入手机号码');
        } else if (!telRule.test(data.cTel)) {
          this.showMessage('手机号码格式不正确');
        } else if (data.addresrow == '') {
          this.showMessage('请选择所在地区');
        } else if (this.data.TName == undefined) {
          this.showMessage('请输入姓名');
        } else if (this.data.TCard == undefined) {
          this.showMessage('请输入身份证号码');
        } else if (!IdRule.test(this.data.TCard)) {
          this.showMessage('请输入正确的身份证号码');
        } else {
          var products = {
            "data": data,
            "address": data.addresrow,
            "province": '',
            "name": data.cName,
            "tel": data.cTel,
            "aid": aid,
            "fasong_type": dataName,
            "personID": data.IdCard ? data.IdCard : '0',
            "orderPrice": orderPrice,
            "totalCount": totalCount,
            "performId": performId,
            "priceID": priceID,
            "pricetitle": pricetitle,
            "quyuID": quyuID,
            "Sprice": Sprice,
            "price": price,
            "mianzhiprice": price,
            "datetime": datetime,
            "default": "0",
            "userid": "-1",
            "pid": 4,
            "paytype": 4
          }; //console.log(products)

          var that = this;
          this.data.products = products;
          ycTicket.doOrder(products, data => {
            if (data.nochushou == 10000) {
              this.showMessage('此项目已售完');
            } else if (data.pass) {
              //更新订单状态
              var id = data.order_no;
              that.data.id = id;
              that.data.fromCartFlag = false; //开始支付

              that._execPay(id);
            } else {
              tt.showModal({
                title: '下单失败',
                content: '请联系客服 400-800-7000',
                showCancel: false,
                success: function (res) {
                  tt.redirectTo({
                    url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                  });
                }
              }); // 下单失败
            }
          });
        }
      } else if (data.cName == '') {
        this.showMessage('请输入姓名');
      } else if (data.cTel == '') {
        this.showMessage('请输入手机号码');
      } else if (!telRule.test(data.cTel)) {
        this.showMessage('手机号码格式不正确');
      } else if (data.addresrow == '') {
        this.showMessage('请选择所在地区');
      } else {
        var products = {
          "data": data,
          "address": data.addresrow,
          "name": data.cName,
          "province": '',
          "tel": data.cTel,
          "aid": aid,
          "fasong_type": dataName,
          "personID": data.IdCard ? data.IdCard : '0',
          "orderPrice": orderPrice,
          "totalCount": totalCount,
          "performId": performId,
          "priceID": priceID,
          "pricetitle": pricetitle,
          "quyuID": quyuID,
          "Sprice": Sprice,
          "price": price,
          "mianzhiprice": price,
          "datetime": datetime,
          "default": "0",
          "userid": "-1",
          "pid": 4,
          "paytype": 4
        };
        console.log(products);
        var that = this;
        this.data.products = products;
        ycTicket.doOrder(products, data => {
          console.log(data);

          if (data.nochushou == 10000) {
            this.showMessage('此项目已售完');
          } else if (data.pass) {
            //更新订单状态
            var id = data.order_no;
            that.data.id = id;
            that.data.fromCartFlag = false; //开始支付

            that._execPay(id);
          } else {
            tt.showModal({
              title: '下单失败',
              content: '请联系客服 400-800-7000',
              showCancel: false,
              success: function (res) {
                tt.redirectTo({
                  url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                });
              }
            }); // 下单失败
          }
        });
      }
    } else if (dataName == '电子票') {
      var data = e.detail.value;

      if (idcards == '是') {
        if (data.dName == '') {
          this.showMessage('请输入姓名');
        } else if (data.dTel == '') {
          this.showMessage('请输入手机号码');
        } else if (!telRule.test(data.dTel)) {
          this.showMessage('手机号码格式不正确');
        } else if (this.data.TName == undefined) {
          this.showMessage('请输入姓名');
        } else if (this.data.TCard == undefined) {
          this.showMessage('请输入身份证号码');
        } else if (!IdRule.test(this.data.TCard)) {
          this.showMessage('请输入正确的身份证号码');
        } else {
          var products = {
            "data": data,
            "address": 0,
            "name": data.dName,
            "province": 0,
            "tel": data.dTel,
            "aid": aid,
            "fasong_type": dataName,
            "personID": data.dIdCard ? data.dIdCard : '0',
            "orderPrice": orderPrice,
            "totalCount": totalCount,
            "performId": performId,
            "priceID": priceID,
            "pricetitle": pricetitle,
            "quyuID": quyuID,
            "price": price,
            "Sprice": Sprice,
            "datetime": datetime,
            "mianzhiprice": price,
            "default": "0",
            "userid": "-1",
            "pid": 4,
            "paytype": 4
          }; //console.log(products)

          var that = this;
          this.data.products = products;
          ycTicket.doOrder(products, data => {
            if (data.nochushou == 10000) {
              this.showMessage('此项目已售完');
            } else if (data.pass) {
              //更新订单状态
              var id = data.order_no;
              that.data.id = id;
              that.data.fromCartFlag = false; //开始支付

              that._execPay(id);
            } else {
              tt.showModal({
                title: '下单失败',
                content: '请联系客服 400-800-7000',
                showCancel: false,
                success: function (res) {
                  tt.redirectTo({
                    url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                  });
                }
              }); // 下单失败
            }
          });
        }
      } else if (data.dName == '') {
        this.showMessage('请输入姓名');
      } else if (data.dTel == '') {
        this.showMessage('请输入手机号码');
      } else if (!telRule.test(data.dTel)) {
        this.showMessage('手机号码格式不正确');
      } else {
        var products = {
          "data": data,
          "address": 0,
          "name": data.dName,
          "province": 0,
          "tel": data.dTel,
          "aid": aid,
          "fasong_type": dataName,
          "personID": data.dIdCard ? data.dIdCard : '0',
          "orderPrice": orderPrice,
          "totalCount": totalCount,
          "performId": performId,
          "priceID": priceID,
          "pricetitle": pricetitle,
          "quyuID": quyuID,
          "price": price,
          "Sprice": Sprice,
          "datetime": datetime,
          "mianzhiprice": price,
          "default": "0",
          "userid": "-1",
          "pid": 4,
          "paytype": 4
        }; //console.log(products)

        var that = this;
        this.data.products = products;
        ycTicket.doOrder(products, data => {
          if (data.nochushou == 10000) {
            this.showMessage('此项目已售完');
          } else if (data.pass) {
            //更新订单状态
            var id = data.order_no;
            that.data.id = id;
            that.data.fromCartFlag = false; //开始支付

            that._execPay(id);
          } else {
            tt.showModal({
              title: '下单失败',
              content: '请联系客服 400-800-7000',
              showCancel: false,
              success: function (res) {
                tt.redirectTo({
                  url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                });
              }
            }); // 下单失败
          }
        });
      }
    } else if (dataName == '现场取票') {
      var data = e.detail.value;

      if (idcards == '是') {
        if (data.sName == '') {
          this.showMessage('请输入姓名');
        } else if (data.sTel == '') {
          this.showMessage('请输入手机号码');
        } else if (!telRule.test(data.sTel)) {
          this.showMessage('手机号码格式不正确');
        } else if (this.data.TName == undefined) {
          this.showMessage('请输入姓名');
        } else if (this.data.TCard == undefined) {
          this.showMessage('请输入身份证号码');
        } else if (!IdRule.test(this.data.TCard)) {
          this.showMessage('请输入正确的身份证号码');
        } else {
          var products = {
            "data": data,
            "address": 0,
            "name": data.dName,
            "province": 0,
            "tel": data.dTel,
            "aid": aid,
            "fasong_type": dataName,
            "personID": data.dIdCard ? data.dIdCard : '0',
            "orderPrice": orderPrice,
            "totalCount": totalCount,
            "performId": performId,
            "priceID": priceID,
            "pricetitle": pricetitle,
            "quyuID": quyuID,
            "price": price,
            "Sprice": Sprice,
            "datetime": datetime,
            "mianzhiprice": price,
            "default": "0",
            "userid": "-1",
            "pid": 4,
            "paytype": 4
          }; //console.log(products)

          var that = this;
          this.data.products = products;
          ycTicket.doOrder(products, data => {
            if (data.nochushou == 10000) {
              this.showMessage('此项目已售完');
            } else if (data.pass) {
              //更新订单状态
              var id = data.order_no;
              that.data.id = id;
              that.data.fromCartFlag = false; //开始支付

              that._execPay(id);
            } else {
              tt.showModal({
                title: '下单失败',
                content: '请联系客服 400-800-7000',
                showCancel: false,
                success: function (res) {
                  tt.redirectTo({
                    url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                  });
                }
              }); // 下单失败
            }
          });
        }
      } else if (data.sName == '') {
        this.showMessage('请输入姓名');
      } else if (data.sTel == '') {
        this.showMessage('请输入手机号码');
      } else if (!telRule.test(data.sTel)) {
        this.showMessage('手机号码格式不正确');
      } else {
        var products = {
          "data": data,
          "address": 0,
          "name": data.sName,
          "province": 0,
          "tel": data.sTel,
          "aid": aid,
          "fasong_type": dataName,
          "personID": data.sIdCard ? data.sIdCard : '0',
          "orderPrice": orderPrice,
          "totalCount": totalCount,
          "performId": performId,
          "priceID": priceID,
          "pricetitle": pricetitle,
          "quyuID": quyuID,
          "price": price,
          "Sprice": Sprice,
          "datetime": datetime,
          "mianzhiprice": price,
          "default": "0",
          "userid": "-1",
          "pid": 4,
          "paytype": 4
        }; //console.log(products)

        var that = this;
        this.data.products = products;
        ycTicket.doOrder(products, data => {
          if (data.nochushou == 10000) {
            this.showMessage('此项目已售完');
          } else if (data.pass) {
            //更新订单状态
            var id = data.order_no;
            that.data.id = id;
            that.data.fromCartFlag = false; //开始支付

            that._execPay(id);
          } else {
            tt.showModal({
              title: '下单失败',
              content: '请联系客服 400-800-7000',
              showCancel: false,
              success: function (res) {
                tt.redirectTo({
                  url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
                });
              }
            }); // 下单失败
          }
        });
      }
    }
  },

  /*
   *开始支付
   * params:
   * id - {int}订单id
   */
  _execPay: function (id) {
    var that = this;
    tt.showLoading({
      title: '正在支付请等待'
    });
    setTimeout(function () {
      tt.hideLoading();
    }, 1000);
    ycTicket.execPay(id, statusCode => {
      if (statusCode != 0) {
        tt.showLoading({
          title: '支付成功'
        }); //显示2秒隐藏加载提示

        setTimeout(function () {
          tt.hideLoading();
        }, 1000);
        var flag = statusCode == 1;
        tt.redirectTo({
          url: '../ycOrder/ycOrder?flag=' + flag + '&id=' + id
        });
      } else {
        tt.showModal({
          title: '下单失败',
          content: '请联系客服 400-800-7000',
          showCancel: false,
          success: function (res) {
            tt.redirectTo({
              url: '../ycOrder/ycOrder'
            });
          }
        });
      }
    });
  },

  /*
   *提示窗口
   *params ：
   *title - 标题
   *content - 内容
   *flag - 是否跳转到"我的页面"
   */
  showTips: function (title, content, flag) {
    tt.showModal({
      title: title,
      content: content,
      showCancel: false,
      success: function (res) {
        if (flag) {
          tt.switchTab({
            url: '/pages/mine/mine'
          });
        }
      }
    });
  },
  showMessage: function (text) {
    var that = this;
    that.setData({
      showMessage: true,
      messageContent: text
    });
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      });
    }, 3000);
  },
  //分享
  onShareAppMessage: function () {
    util.sharePage();
  }
});